<?php

namespace app\http\middleware;

use app\admin\controller\CommonController;
use app\admin\controller\JwtAuth;
use app\admin\controller\ResponseJson;
use think\Db;

class LoginAuth
{
    public function handle($request, \Closure $next)
    {
        $token = $request->header('token');
        if ($token){
            $jwtAuth= JwtAuth::getInstance();
            $jwtAuth->setToken($token);
            if ($jwtAuth->validate() && $jwtAuth->verify()){
                $res_url = explode('?', $request->url());
                $permission_list = $this->GetPermissionList($token);
                if (!in_array($res_url[0],$permission_list)){
                    //不在路由组 视为非法请求
                     return returnJson(UN_ACCESS,[],'非法访问');
                }
                return $next($request);
            }else{
                //token验证失败
                return returnJson(LOGIN_OUT_CODE,[],'登陆过期');
            }


        }else{
            return returnJson(LOGIN_OUT_CODE,[],'参数不完整');
        }
    }

    //获取当前用户权限
    public function GetPermissionList($token){
        $common = new CommonController();
        $res=Db::table('user a')
            ->alias('a')
            ->join('user_role b','a.id = b.user_id')
            ->join('role c','c.id = b.role_id')
            ->join('permission_role d','d.role_id = c.id')
            ->join('permission e','e.id = d.permission_id')
            ->where('a.delete_flag','=',0)
            ->where('a.status','=',0)
            ->where('b.delete_flag','=',0)
            ->where('b.status','=',0)
            ->where('c.delete_flag','=',0)
            ->where('c.status','=',0)
            ->where('d.delete_flag','=',0)
            ->where('d.status','=',0)
            ->where('e.delete_flag','=',0)
            ->where('e.status','=',0)
            ->where('a.id','=',$common->getUserId($token))
            ->field('e.route')
            ->select();
        $list=[];
        if (!empty($res)){
            foreach ($res as $key=>$val){
                //过滤空路由
                if (count($val)>0){
                    $arr_route=explode(',',$val['route']);
                    foreach ($arr_route as $k=>$v){
                        if (strlen($v)>0){
                            $list[]=$v;
                        }

                    }

                }
            }
        }
        //去重
        $result = array_unique($list);
//        Log::error($result);
        return $result;

    }
}
